package com.hmall.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.AddressClient;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import org.aspectj.weaver.ast.Var;
import org.springframework.amqp.core.Correlation;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private ItemClient itemClient;

    @Autowired
    private AddressClient addressClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //创建订单
    @Override
    public Long createOrder(Map<String, Object> map, Long userId) {
        //                - 1）根据雪花算法生成订单id
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
//                - 2）商品微服务提供FeignClient，实现根据id查询商品的接口
//                - 3）根据itemId查询商品信息
/*        Integer itemId = (Integer) map.get("itemId");
        Long id1 = Long.valueOf(map.get("itemId").toString());
        Item item = itemClient.getItemById(Long.valueOf(id1));*/
        Long itemId = Long.valueOf(map.get("itemId").toString());
        Item item = itemClient.getItemById(itemId);

//                - 4）基于商品价格、购买数量计算商品总价：totalFee
        Integer num = (Integer) map.get("num");
        Long price = item.getPrice();
        Long totalFee = num * price;
//                - 5）封装Order对象，初识status为未支付
        Order order = new Order();
        order.setId(id);
        order.setStatus(1);
        order.setTotalFee(totalFee);
        order.setUserId(userId);
        order.setCloseTime(DateUtil.date());
        Integer paymentType = (Integer) map.get("paymentType");
        order.setPaymentType(paymentType);
//                - 6）将Order写入数据库tb_order表中
        orderMapper.insert(order);
//                - 7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum((Integer) num);
        orderDetail.setName(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetail.setCreateTime(DateUtil.date());
        orderDetailMapper.insert(orderDetail);
//                - 8）将user-service的根据id查询地址接口封装为FeignClient
//                - 9）根据addressId查询user-service服务，获取地址信息
        Address address = addressClient.getById(Long.valueOf(map.get("addressId").toString()));
//                - 10）将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setCity("");
        orderLogistics.setTown("");
        orderLogistics.setStreet("");
        if (address.getProvince() != null){
            orderLogistics.setProvince(address.getProvince());
        }else if (address.getCity() != null){
            orderLogistics.setCity(address.getCity());
        }else if (address.getTown() != null){
            orderLogistics.setTown(address.getTown());
        }else if (address.getStreet() != null){
            orderLogistics.setStreet(address.getStreet());
        }
        orderLogistics.setCreateTime(DateUtil.date());
        orderLogisticsMapper.insert(orderLogistics);
//                - 11）在item-service提供减库存接口，并编写FeignClient
//                - 12）调用item-service的减库存接口
        itemClient.deleteStock(item.getId(),num);
        //发送消息
        String orderId = order.getId().toString();
        Message message = MessageBuilder.withBody(orderId.getBytes(StandardCharsets.UTF_8)).setHeader("x-delay", 3000).build();
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("delay.direct","delay",message,correlationData);
        return order.getId();
    }

    //超时订单
    @Override
    public void listenOrderDelayedQueue(String orderId) {
        Long orderIdToLong = Long.valueOf(orderId);
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getId,orderIdToLong);
        Order order = orderMapper.selectOne(qw);
        Integer status = order.getStatus();
        //判断是否继续
        if (status == 1){
            LambdaQueryWrapper<OrderDetail> oqw = new LambdaQueryWrapper<>();
            oqw.eq(OrderDetail::getOrderId,orderIdToLong);
            //获取订单详情
            OrderDetail orderDetail = orderDetailMapper.selectOne(oqw);
            Long itemId = orderDetail.getItemId();
            //购买数量
            Integer num = orderDetail.getNum();
            itemClient.addStock(itemId,num);
        }

    }

}
